<?php

namespace app\portal\controller;

use app\admin\model\Commitment;
use app\admin\model\Paper;
use app\admin\model\Question;
use app\admin\model\TestAnswer;
use app\base\model\User;
use app\common\controller\PortalBase;
use think\Request;


class My extends PortalBase {
  protected $modelRoom, $modelUser, $modelPaper, $modelQuestion, $modelTest, $modelTestAnswer;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->modelRoom = new \app\admin\model\Room();
    $this->modelUser = new User();
    $this->modelPaper = new Paper();
    $this->modelQuestion = new Question();
    $this->modelTest = new \app\admin\model\Test();
    $this->modelTestAnswer = new  TestAnswer();
  }

  public function _initialize() {
    parent::_initialize();
  }

  public function index() {
    $nowTimestamp = time();

    //获取正式考试
    $userInfo = $this->modelUser->find($this->uid);
    //获取模拟考试
    $papers = $this->modelTestAnswer
      ->order('create_time DESC')
      ->where('uid', $this->uid)->select();


    if (request()->isAjax()) {
      $this->result($papers, 1);
    }

    $commitment = cmf_get_commitment();

    return view('', [
      'papers'       => $papers,
      'nowTimestamp' => $nowTimestamp,
      'userInfo'     => $userInfo,
      'commitment'   => $commitment,
    ]);

  }

  public function password() {
    if (!request()->isPost()) {
      return view();
    }
    $form = input('form/a', NULL, 'trim');
    if ($form['password'] != $form['password2'])
      $this->error('两次密码不相同');
    $data['salt'] = rand(100000, 999999);
    $data['password'] = $this->modelUser->createPassword($form['password'], $data['salt']);
    try {
      $this->modelUser->save($data, ['id' => $this->uid]);
    } catch (Exception $e) {
      $this->error($e->getMessage());
    }
    $this->success(lang('success'), url('knowledge/index'));

  }

  public function getCommitment() {
    $content = cmf_get_commitment()['content'];
    if (request()->isAjax()) {
      $this->result($content, 1);
    }

    return $content;

  }

  public function view() {
    $id = input('id/d', 0, 'abs');
    $testAnswer = $id > 0 ? $this->modelTestAnswer->find($id) : [];
    $paperId = $testAnswer['paper_id'];
    $paper = $this->modelTest->find($paperId);
    $qIds = json_decode($paper['questions']);
    $answers = json_decode($paper['answers']);
    $questions = $this->modelQuestion->getQuestionAnswer($qIds);

    return view('', [
      'paper'      => $paper,
      'testAnswer' => $testAnswer,
      'realname'   => session('user_info')['realname'],
      'questions'  => $questions,
      'answers'    => $answers]);
  }
}
